<!DOCTYPE html>
<html class="x-admin-sm">

<head>
  <meta charset="UTF-8">
  <title>设备/终端导表入库</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <link rel="stylesheet" href="../../css/font.css">
  <link rel="stylesheet" href="../../css/xadmin.css">
  <script type="text/javascript" src="../../lib/layui/layui.js" charset="utf-8"></script>
  <script type="text/javascript" src="../../js/xadmin.js"></script>
  <script src="../../js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="../../js/app.js" type="text/javascript" charset="utf-8"></script>
  <style type="text/css">
    .form-position {
      margin: 0.85rem;
      padding-top: 8px;
      background-color: white;

    }
  </style>
</head>

<body>
  <div class="x-nav">
    <span class="layui-breadcrumb">
      <a href="">首页</a>
      <a href="">演示</a>
      <a>
        <cite>导航元素</cite></a>
    </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
      onclick="location.reload()" title="刷新">
      <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
  </div>
  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md12">
        <div class="layui-card">
          <div class="layui-card-body ">
            <blockquote class="layui-elem-quote" style="margin-top: 10px; width: 97%;">
              <a href="http://116.62.7.204:8080/inventory_development/static/终端设备入库样表.xlsx">下载样表</a>
            </blockquote>
            <div class="layui-collapse" lay-filter="test">
              <div class="layui-colla-item">
                <h2 class="layui-colla-title">选择Excel表格入库<i class="layui-icon layui-colla-icon"></i></h2>
                <div class="layui-colla-content" style="display:flex;">

                  <div class="layui-inline layui-show-xs-block" style="margin-top: 7.2px;margin-left: 4px;">
                    <input type="file" id='inputfilename'>
                  </div>
                  <div class="layui-inline layui-show-xs-block" style="margin-top: 7.2px;margin-left: 4px;">
                    <button class="layui-btn layui-btn-normal" onclick="readWorkbookFromLocalFile()">读取Excel表格</button>
                  </div>
                  <div class="layui-inline layui-show-xs-block layui-hide" id="InstorageToEquipment"
                    style="margin-top: 7.2px;margin-left: 10px;">
                    <button class="layui-btn" onclick="InstorageToEquipment_Ajax()">导入设备库</button>
                  </div>
                  <div class="layui-inline layui-show-xs-block layui-hide" id="InstorageToTerminal"
                    style="margin-top: 7.2px;margin-left: 10px;">
                    <button class="layui-btn" onclick="InstorageToTerminal_Ajax()">导入终端库</button>
                  </div>
                </div>
                <div id="result"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <script src="Select.js" type="text/javascript" charset="utf-8"></script> -->
    <!-- 导表入库 -->
    <script src="../../js/xlsx.core.min.js"></script>
    <script>
      // 创造workbook对象
      var newJsonData = null;

      function readWorkbookFromLocalFile() {
        var file = document.getElementById('inputfilename').files[0];
        if (file) {
          var reader = new FileReader();

          reader.onload = function (e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {
              type: 'binary'
            });
            readWorkbook(workbook);
          };
          reader.readAsBinaryString(file);
          $('#InstorageToEquipment').removeClass('layui-hide');
          $('#InstorageToTerminal').removeClass('layui-hide');
        } else {
          layer.msg('请先选择文件！')
        }

      }

      // 将excel内容转换为csv和json
      var csv = '';

      function readWorkbook(workbook) {
        var sheetNames = workbook.SheetNames; // 工作表名称集合
        var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet的内容

        csv = XLSX.utils.sheet_to_csv(worksheet);
        document.getElementById('result').innerHTML = csv2table(csv);

        var json = XLSX.utils.sheet_to_json(worksheet);
        for (var i = 0; i < json.length; i++) {
          delete json[i]['序号'];
        }
        var jsonData = JSON.stringify(json, null, "\t");
        newJsonData = jsonData.replace(/\u54C1\u540D/g, 'typicalName');
        newJsonData = newJsonData.replace(/\u54C1\u724C/g, 'brand');
        newJsonData = newJsonData.replace(/\u578B\u53F7/g, 'typicalModel');
        newJsonData = newJsonData.replace(/\u4E32\u53F7/g, 'imei');
        newJsonData = newJsonData.replace(/\u5165\u5E93\u65F6\u95F4/g, 'storageTime');
      }

      // 将csv转换成简单的表格，会忽略单元格合并，在第一行和第一列追加类似excel的索引
      function csv2table(csv) {
        var html = '<table class="layui-table layui-form">';
        var rows = csv.split('\n');
        // console.log(rows);

        rows.pop(); // 最后一行没用的
        rows.forEach(function (row, idx) {
          var columns = row.split(',');
          // console.log(columns);

          columns.unshift(idx + 1); // 添加行索引
          if (idx == 0) { // 添加列索引
            html += '<tr>';
            for (var i = 0; i < columns.length; i++) {
              html += '<th>' + (i == 0 ? '' : String.fromCharCode(65 + i - 1)) + '</th>';
            }
            html += '</tr>';
          }
          html += '<tr>';
          columns.forEach(function (column) {
            html += '<td>' + column + '</td>';
          });
          html += '</tr>';
        });
        html += '</table>';
        return html;
      }

      // 将数据传送给后台
      var operator = app.getUserGlobalInfo();
      var respository_Id = operator.repositoryList[0].repositoryId;
      var user_Id = operator.userId;

      //将设备入库
      function InstorageToEquipment_Ajax() {
        layer.confirm('确认要导入到设备库吗？', {
          title: '提示信息',
          icon: 3,
          btn: ['确认', '取消'],
          yes: function () {
            var sessionId = (JSON.parse(localStorage.getItem("userInfo"))).sessionId;
            $.ajax({
              url: app.ServerUrl + 'v1/material/inStorageEquipmentByExcel',
              type: "POST",
              contentType: "application/json;charset=UTF-8",
              dataType: "json",
              async: true,
              headers: {
                "Authorization": sessionId
              },
              data: JSON.stringify({
                "equipmentBo2List": JSON.parse(newJsonData),
                "repositoryId": respository_Id,
                "userId": user_Id
              }),
              beforeSend: function () {
                loading = layer.load();
              },
              success: function (data) {
                layer.close(loading);
                if (data.resultStatus === -1) {
                  layer.open({
                    content: data.objs[0],
                    btnAlign: 'r',
                    anim: 5,
                    icon: 7,
                    cancel: function () {},
                    yes: function () {
                      window.location.reload();
                    }
                  })
                } else if (data.resultStatus == 1 && data.objs != null) {
                  // imei：数据库已存在的串号
                  var objs = data.objs[0];
                  var msg = data.resultIns + '。\n已存在的串号有：\n';
                  for (var i = 0; i < objs.length; i++) {
                    msg += objs[i].imei;
                    msg += '；\n';
                  }
                  layer.open({
                    title: '提示信息',
                    content: msg,
                    btnAlign: 'c',
                    anim: 5,
                    icon: 6,
                    yes: function (index) {
                      layer.close(index);
                    }
                  })
                } else {
                  layer.open({
                    content: '入库成功',
                    btnAlign: 'c',
                    anim: 5,
                    icon: 6,
                    yes: function () {
                      window.location.reload();
                    }
                  })
                }
              },
              error: function (data) {
                layer.open({
                  content: '入库失败',
                  btnAlign: 'c',
                  anim: 5,
                  icon: 5,
                  cancel: function () {},
                  yes: function () {
                    window.location.reload();
                  }
                })
              }
            })

          },
          cancel: function () {

          }
        })
      }

      // 将终端入库
      function InstorageToTerminal_Ajax() {
        layer.confirm('确认要导入到终端库吗？', {
          title: '提示信息',
          icon: 3,
          btn: ['确认', '取消'],
          yes: function () {
            var sessionId = (JSON.parse(localStorage.getItem("userInfo"))).sessionId;
            $.ajax({
              url: app.ServerUrl + 'v1/material/inStorageTerminalByExcel',
              type: "POST",
              contentType: "application/json;charset=UTF-8",
              dataType: "json",
              async: true,
              headers: {
                "Authorization": sessionId
              },
              data: JSON.stringify({
                "terminalBo2List": JSON.parse(newJsonData),
                "repositoryId": respository_Id,
                "userId": user_Id
              }),
              beforeSend: function () {
                loading = layer.load();
              },
              success: function (data) {
                layer.close(loading);
                if (data.resultStatus === -1) {
                  layer.open({
                    content: data.objs[0],
                    btnAlign: 'r',
                    anim: 5,
                    icon: 7,
                    cancel: function () {},
                    yes: function () {
                      window.location.reload();
                    }
                  })
                } else if (data.resultStatus == 1 && data.objs != null) {
                  // imei：数据库已存在的串号
                  var objs = data.objs[0];
                  var msg = data.resultIns + '。\n已存在的串号有：\n';
                  for (var i = 0; i < objs.length; i++) {
                    msg += objs[i].imei;
                    msg += '；\n';
                  }
                  layer.open({
                    title: '提示信息',
                    content: msg,
                    btnAlign: 'c',
                    anim: 5,
                    icon: 6,
                    yes: function (index) {
                      layer.close(index);
                    }
                  })
                } else {
                  layer.open({
                    content: '入库成功',
                    btnAlign: 'c',
                    anim: 5,
                    icon: 6,
                    yes: function () {
                      window.location.reload();
                    }
                  })
                }
              },
              error: function (data) {
                layer.open({
                  content: '入库失败',
                  btnAlign: 'c',
                  anim: 5,
                  icon: 5,
                  cancel: function () {},
                  yes: function () {
                    window.location.reload();
                  }
                })
              }
            })
          },
          cancel: function () {

          }
        })
      }
    </script>

    <script>
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?b393d153aeb26b46e9431fabaf0f6190";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
</body>

</html>